/*
 * @Author: your name
 * @Date: 2024-04-26 12:46:35
 * @LastEditTime: 2024-04-26 12:55:24
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \.leetcode\654.最大二叉树.cpp
 */
/*
 * @lc app=leetcode.cn id=654 lang=cpp
 *
 * [654] 最大二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* traversal(vector<int>& nums, int left, int right) {

        if(left > right) return nullptr;

        // 找到数组中的最大的值的下标
        int max_val_index = left;
        for(int index = left; index <= right; index++){
            if(nums[index] > nums[max_val_index]){
                max_val_index = index;
            }
        }
        // 创建当前数组的根节点
        TreeNode* root = new TreeNode(nums[max_val_index]);

        // 分割左右两边的数组并递归
        root->left = traversal(nums, left, max_val_index - 1);
        root->right = traversal(nums, max_val_index+1, right);

        return root;

    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        if(nums.size() == 0){
            return nullptr;
        }
        return traversal(nums, 0, nums.size() - 1);
    }
};
// @lc code=end

